package com.farmer.training.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.farmer.common.entity.TrainingCourse;
import com.farmer.common.result.Result;
import com.farmer.training.mapper.TrainingMapper;
import com.farmer.training.service.TrainingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 培训课程服务实现类
 */

@Slf4j
@Service
public class TrainingServiceImpl implements TrainingService {

    @Autowired
    private TrainingMapper trainingMapper;

    @Override
    public Result<?> getCourseList(Integer pageNum, Integer pageSize, String category, String courseType, String status, String keyword) {
        try {
            Page<TrainingCourse> page = new Page<>(pageNum, pageSize);
            QueryWrapper<TrainingCourse> queryWrapper = new QueryWrapper<>();

            // 分类过滤
            if (StringUtils.hasText(category)) {
                queryWrapper.eq("category", category);
            }

            // 课程类型过滤
            if (StringUtils.hasText(courseType)) {
                queryWrapper.eq("course_type", courseType);
            }

            // 状态过滤
            if (StringUtils.hasText(status)) {
                queryWrapper.eq("status", status);
            }

            // 关键词搜索（标题、描述、讲师姓名）
            if (StringUtils.hasText(keyword)) {
                queryWrapper.and(wrapper -> wrapper
                        .like("title", keyword)
                        .or()
                        .like("description", keyword)
                        .or()
                        .like("instructor_name", keyword)
                );
            }

            // 按创建时间倒序
            queryWrapper.orderByDesc("create_time");

            Page<TrainingCourse> coursePage = trainingMapper.selectPage(page, queryWrapper);

            Map<String, Object> result = new HashMap<>();
            result.put("records", coursePage.getRecords());
            result.put("total", coursePage.getTotal());
            result.put("pageNum", pageNum);
            result.put("pageSize", pageSize);

            return Result.success("获取培训课程列表成功", result);
        } catch (Exception e) {
            log.error("获取培训课程列表失败：{}", e.getMessage(), e);
            return Result.error("获取培训课程列表失败");
        }
    }

    @Override
    public Result<?> getCourseById(Long courseId) {
        try {
            if (courseId == null) {
                return Result.error("课程ID不能为空");
            }

            TrainingCourse course = trainingMapper.selectById(courseId);
            if (course == null) {
                return Result.error("课程不存在");
            }

            return Result.success("获取课程详情成功", course);
        } catch (Exception e) {
            log.error("获取课程详情失败：{}", e.getMessage(), e);
            return Result.error("获取课程详情失败");
        }
    }

    @Override
    public Result<?> addCourse(TrainingCourse course) {
        try {
            if (course == null) {
                return Result.error("课程信息不能为空");
            }

            if (!StringUtils.hasText(course.getTitle())) {
                return Result.error("课程标题不能为空");
            }

            // 设置默认值
            if (course.getCurrentStudents() == null) {
                course.setCurrentStudents(0);
            }
            if (course.getStatus() == null) {
                course.setStatus("DRAFT");
            }

            int result = trainingMapper.insert(course);
            if (result > 0) {
                return Result.success("添加培训课程成功", course);
            } else {
                return Result.error("添加培训课程失败");
            }
        } catch (Exception e) {
            log.error("添加培训课程失败：{}", e.getMessage(), e);
            return Result.error("添加培训课程失败");
        }
    }

    @Override
    public Result<?> updateCourse(TrainingCourse course) {
        try {
            if (course == null || course.getId() == null) {
                return Result.error("课程ID不能为空");
            }

            TrainingCourse existingCourse = trainingMapper.selectById(course.getId());
            if (existingCourse == null) {
                return Result.error("课程不存在");
            }

            int result = trainingMapper.updateById(course);
            if (result > 0) {
                return Result.success("更新课程信息成功");
            } else {
                return Result.error("更新课程信息失败");
            }
        } catch (Exception e) {
            log.error("更新课程信息失败：{}", e.getMessage(), e);
            return Result.error("更新课程信息失败");
        }
    }

    @Override
    public Result<?> deleteCourse(Long courseId) {
        try {
            if (courseId == null) {
                return Result.error("课程ID不能为空");
            }

            TrainingCourse course = trainingMapper.selectById(courseId);
            if (course == null) {
                return Result.error("课程不存在");
            }

            int result = trainingMapper.deleteById(courseId);
            if (result > 0) {
                return Result.success("删除课程成功");
            } else {
                return Result.error("删除课程失败");
            }
        } catch (Exception e) {
            log.error("删除课程失败：{}", e.getMessage(), e);
            return Result.error("删除课程失败");
        }
    }

    @Override
    public Result<?> updateCourseStatus(Long courseId, String status) {
        try {
            if (courseId == null) {
                return Result.error("课程ID不能为空");
            }

            if (!StringUtils.hasText(status)) {
                return Result.error("课程状态不能为空");
            }

            TrainingCourse course = trainingMapper.selectById(courseId);
            if (course == null) {
                return Result.error("课程不存在");
            }

            course.setStatus(status);
            int result = trainingMapper.updateById(course);
            if (result > 0) {
                return Result.success("更新课程状态成功");
            } else {
                return Result.error("更新课程状态失败");
            }
        } catch (Exception e) {
            log.error("更新课程状态失败：{}", e.getMessage(), e);
            return Result.error("更新课程状态失败");
        }
    }

    @Override
    public Result<?> getRecommendedCourses(Integer limit) {
        try {
            if (limit == null || limit <= 0) {
                limit = 10;
            }

            QueryWrapper<TrainingCourse> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("status", "PUBLISHED")
                    .orderByDesc("rating", "create_time")
                    .last("LIMIT " + limit);

            List<TrainingCourse> courseList = trainingMapper.selectList(queryWrapper);
            return Result.success("获取推荐课程成功", courseList);
        } catch (Exception e) {
            log.error("获取推荐课程失败：{}", e.getMessage(), e);
            return Result.error("获取推荐课程失败");
        }
    }

    @Override
    public Result<?> getCategoryList() {
        try {
            QueryWrapper<TrainingCourse> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("DISTINCT category")
                    .isNotNull("category")
                    .ne("category", "");

            List<TrainingCourse> courses = trainingMapper.selectList(queryWrapper);
            List<String> categories = courses.stream()
                    .map(TrainingCourse::getCategory)
                    .filter(Objects::nonNull)
                    .distinct()
                    .toList();

            return Result.success("获取课程分类成功", categories);
        } catch (Exception e) {
            log.error("获取课程分类失败：{}", e.getMessage(), e);
            return Result.error("获取课程分类失败");
        }
    }

    @Override
    public Result<?> getCoursesByInstructor(Long instructorId, Integer pageNum, Integer pageSize) {
        try {
            if (instructorId == null) {
                return Result.error("讲师ID不能为空");
            }

            Page<TrainingCourse> page = new Page<>(pageNum, pageSize);
            QueryWrapper<TrainingCourse> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("instructor_id", instructorId)
                    .orderByDesc("create_time");

            Page<TrainingCourse> coursePage = trainingMapper.selectPage(page, queryWrapper);

            Map<String, Object> result = new HashMap<>();
            result.put("records", coursePage.getRecords());
            result.put("total", coursePage.getTotal());
            result.put("pageNum", pageNum);
            result.put("pageSize", pageSize);

            return Result.success("获取讲师课程列表成功", result);
        } catch (Exception e) {
            log.error("获取讲师课程列表失败：{}", e.getMessage(), e);
            return Result.error("获取讲师课程列表失败");
        }
    }

    @Override
    public Result<?> increaseEnrollmentCount(Long courseId) {
        try {
            if (courseId == null) {
                return Result.error("课程ID不能为空");
            }

            TrainingCourse course = trainingMapper.selectById(courseId);
            if (course == null) {
                return Result.error("课程不存在");
            }

            course.setCurrentStudents(course.getCurrentStudents() + 1);
            int result = trainingMapper.updateById(course);
            if (result > 0) {
                return Result.success("增加报名人数成功");
            } else {
                return Result.error("增加报名人数失败");
            }
        } catch (Exception e) {
            log.error("增加报名人数失败：{}", e.getMessage(), e);
            return Result.error("增加报名人数失败");
        }
    }

    @Override
    public Result<?> decreaseEnrollmentCount(Long courseId) {
        try {
            if (courseId == null) {
                return Result.error("课程ID不能为空");
            }

            TrainingCourse course = trainingMapper.selectById(courseId);
            if (course == null) {
                return Result.error("课程不存在");
            }

            if (course.getCurrentStudents() > 0) {
                course.setCurrentStudents(course.getCurrentStudents() - 1);
                int result = trainingMapper.updateById(course);
                if (result > 0) {
                    return Result.success("减少报名人数成功");
                } else {
                    return Result.error("减少报名人数失败");
                }
            } else {
                return Result.error("当前报名人数已为0");
            }
        } catch (Exception e) {
            log.error("减少报名人数失败：{}", e.getMessage(), e);
            return Result.error("减少报名人数失败");
        }
    }

    @Override
    public Result<?> getCourseStatistics() {
        try {
            QueryWrapper<TrainingCourse> queryWrapper = new QueryWrapper<>();
            Long totalCourses = trainingMapper.selectCount(queryWrapper);

            queryWrapper.clear();
            queryWrapper.eq("status", "PUBLISHED");
            Long publishedCourses = trainingMapper.selectCount(queryWrapper);

            queryWrapper.clear();
            queryWrapper.eq("status", "ONGOING");
            Long ongoingCourses = trainingMapper.selectCount(queryWrapper);

            queryWrapper.clear();
            queryWrapper.eq("status", "COMPLETED");
            Long completedCourses = trainingMapper.selectCount(queryWrapper);

            Map<String, Object> statistics = new HashMap<>();
            statistics.put("totalCourses", totalCourses);
            statistics.put("publishedCourses", publishedCourses);
            statistics.put("ongoingCourses", ongoingCourses);
            statistics.put("completedCourses", completedCourses);

            return Result.success("获取课程统计信息成功", statistics);
        } catch (Exception e) {
            log.error("获取课程统计信息失败：{}", e.getMessage(), e);
            return Result.error("获取课程统计信息失败");
        }
    }
}
